import { Toast } from "vant";
//验证码sdk
const InspireCloud = require("@byteinspire/js-sdk");
const serviceId = "qcljo8";
const inspirecloud = new InspireCloud({ serviceId }); 

//手机正则表达式
let reg_tel =
  /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;

//发送验证码定时器
let loopTiming = function (that) {
  setTimeout(() => {
    if (--that.vtime == 0) {
      that.vbtnMessage = "发送验证码";
      that.isSend = false;
      that = null;
    } else {
      that.vbtnMessage = `倒计时${that.vtime}S`;
      loopTiming(that);
    }
  }, 1000);
};

//发送验证码
/* 
    使用call方法调用传入校验实例
    vtime
    isSend:是否处于发送状态
    vbtnMessage:发送按钮文字
    phone:接收验证码的电话
*/
function sendVerfiedCode() {
  const toast1 = Toast.loading({
    duration: 1000,
    forbidClick: true,
    message: "发送验证码中...",
    onOpened: async () => {
      await inspirecloud
        .run("sendVerfiedCode", {
          phoneNumber: this.phone,
        })
        .then((res) => {
          if (res.success) {
            this.vtime = 60;
            this.isSend = true;
            this.vbtnMessage = `倒计时${this.vtime}S`;
            loopTiming(this);
            toast1.clear();
            const toast2 = Toast.success({
              duration: 1000,
              forbidClick: true,
              message: "已发送验证码!",
              onClose: () => {
                toast2.clear();
              },
            });
          }
        })
        .catch(err => {
            const toast2 = Toast.fail({
                duration: 1000,
                forbidClick: true,
                message: "发送失败!",
                onClose: () => {
                  toast2.clear();
                },
              });
        });
    },
  });
}

//校验验证码
async function VerfyingCode(phoneNumber,code){
    let res = await inspirecloud.run('verifyingCode', {
        phoneNumber,
        code
      });
    return Promise.resolve(res)
}

export {sendVerfiedCode,VerfyingCode, reg_tel };
